<?php
namespace app\util;

use think\facade\Log;

class TLPAYUtil{
    /**
     * RSA签名
     */
    public static function Sign(array $array, string $private_key){
        ksort($array);
        $bufSignSrc = TLPAYUtil::ToUrlParams($array);
        $private_key = chunk_split($private_key , 64, "\n");
        $key = "-----BEGIN RSA PRIVATE KEY-----\n".wordwrap($private_key)."-----END RSA PRIVATE KEY-----";
        if(openssl_sign($bufSignSrc, $signature, $key )){
            Log::error('sign success');
        }else{
            Log::error('sign fail');
        }
        $sign = base64_encode($signature);
        return $sign;
    }

    /**
     * 校验签名
     * @param array 参数
     * @param unknown_type appkey
     */
    public static function ValidSign(array $array, string $public_key){
        $sign = $array['sign'];
        unset($array['sign']);
        ksort($array);
        $bufSignSrc = TLPAYUtil::ToUrlParams($array);
        $public_key = chunk_split($public_key , 64, "\n");
        $key = "-----BEGIN PUBLIC KEY-----\n".$public_key."-----END PUBLIC KEY-----";
        $result = openssl_verify($bufSignSrc, base64_decode($sign), $key );
        if($result == 1){
            Log::error('valid sign success');
        } else if($result == 0){
            Log::error('valid sign invalid');
        } else {
            Log::error('ugly, error checking signature');
        }
        return $result;
    }

    public static function ToUrlParams(array $array)
    {
        $buff = "";
        foreach ($array as $k => $v)
        {
            if($v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
}
?>